//
//  Alamofire+Rx.swift
//  BLink
//
//  Created by melvyn on 2018/9/1.
//  Copyright © 2018 NEET. All rights reserved.
//

import Foundation
import RxSwift
import Alamofire

extension Request {
    public static func serializeResponseEntity<T: Codable>(
        modelClass: T.Type,
        response: HTTPURLResponse?,
        data: Data?,
        error: Error?)
        -> Result<T>
    {
        guard error == nil else { return .failure(error!) }
        
        guard let validData = data, validData.count > 0 else {
            return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength))
        }
        
        // Decryption        
        do {
            let json = try JSONAdapter.model(of: modelClass, from: validData)
            return .success(json)
        } catch {
            return .failure(AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error)))
        }
    }
}

extension DataRequest {
    public static func entityResponseSerializer<T: Codable>(modelClass: T.Type) -> DataResponseSerializer<T> {
        return DataResponseSerializer { _, response, data, error in
            return Request.serializeResponseEntity(modelClass: modelClass, response: response, data: data, error: error)
            }
    }
    
    @discardableResult
    public func responseEntity<T: Codable>(
        queue: DispatchQueue? = nil,
        modelClass: T.Type,
        completionHandler: @escaping (DataResponse<T>) -> Void)
        -> Self
    {
        return response(
            queue: queue,
            responseSerializer: DataRequest.entityResponseSerializer(modelClass: modelClass),
            completionHandler: completionHandler
        )
    }
}
